﻿using System.Linq.Expressions;

// 二元表达式
Expression<Func<int, int>> fcunExp = (y) => 5 + y;
ConstantExpression constExp = Expression.Constant(5); // Left
ParameterExpression paramExp = Expression.Parameter(typeof(int), "y"); // Right
BinaryExpression binaryExp = Expression.Add(constExp, paramExp); // 二元表达式，Body
// 最终表达式
Expression<Func<int, int>> fcunExp2 = Expression.Lambda<Func<int, int>>(binaryExp, new ParameterExpression[] { paramExp });

var result = fcunExp2.Compile().Invoke(10);
Console.WriteLine(result);

Expression<Func<int, int, int>> fcunExp3 = (int x, int y) => x + y;
ParameterExpression param2Exp = Expression.Parameter(typeof(int), "x");
ParameterExpression param3Exp = Expression.Parameter(typeof(int), "y");
BinaryExpression binary2Exp = Expression.Add(param2Exp, param3Exp);

Expression<Func<int, int, int>> fcunExp4 = Expression.Lambda<Func<int, int, int>>(binary2Exp, new ParameterExpression[] { param2Exp, param3Exp });




Expression<Func<int,int, int>> fcunExp5 = (x, y) => 5 + y * y - x;
// Left
ConstantExpression constExp2 = Expression.Constant(5);
// center 
ParameterExpression paramExp5 = Expression.Parameter(typeof(int), "y");
BinaryExpression binary3Exp = Expression.Multiply(paramExp5, paramExp5);
// Rigth
ParameterExpression paramExp6 = Expression.Parameter(typeof(int), "x");
BinaryExpression binary4Exp = Expression.Add(constExp2, binary3Exp);
BinaryExpression binary5Exp = Expression.Subtract(binary4Exp,paramExp6);
Expression<Func<int, int, int>> fcunExp6 = Expression.Lambda<Func<int, int, int>>(binary5Exp, new ParameterExpression[] { paramExp5, paramExp6 });

var res2 = fcunExp6.Compile().Invoke(5,6);
Console.WriteLine($"res2:{res2}");


Expression<Func<Student,string>> exp = (s)=>s.Id.ToString();

ParameterExpression p = Expression.Parameter(typeof(Student), "s");
MemberExpression m = Expression.Property(p, "Id");
MethodCallExpression methodCallExp = Expression.Call(m, "ToString", null);
Expression<Func<Student, string>> fun = Expression.Lambda<Func<Student, string>>(methodCallExp, new ParameterExpression[] {p });

var res3 = fun.Compile().Invoke(new Student {Id=5,Name="黄某人" });
Console.WriteLine(res3);
class Student
{
    public int Id { get; set; }

    public string Name { get; set; }
}